package com.ttbj.shiro.realm;

import java.text.MessageFormat;
import java.util.List;


import org.apache.commons.lang.StringUtils;
import org.apache.shiro.config.Ini;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import com.ttbj.api.dto.PermissionDto;
import com.ttbj.api.salesman.PermissionService;


public class ShiroDefinitionSectionMetaSource implements FactoryBean<Ini.Section>{

	@Autowired
	@Qualifier("permissionService")
	private PermissionService permissionService;
	//注入默认的授权定义
	private String filterChainDefinitions;
	
	public void setFilterChainDefinitions(String filterChainDefinitions) {
		this.filterChainDefinitions = filterChainDefinitions;
	}

	//格式化premission数据，符合shiro的格式，如：perm["dept:add"]
	private static final String PERMS = "perms[{0}]";
	
	@Override
    public Ini.Section getObject() throws Exception {
		System.out.println("ShiroDefinitionSectionMetaSource..已进入。。。。。。。。。。");
        Ini ini = new Ini();
        ini.load(filterChainDefinitions);
        Ini.Section section = ini.getSection(Ini.DEFAULT_SECTION_NAME);
        //通过角色id查询权限资源
        List<PermissionDto> permissionDtos = this.permissionService.queryAll(null);
        for (PermissionDto permissionDto : permissionDtos) {
            String uri = permissionDto.getUrl();
            String permission = permissionDto.getPermission();
            if(StringUtils.isNotEmpty(uri) && StringUtils.isNotEmpty(permission)){
                section.put(uri, MessageFormat.format(PERMS, permission));
            }
        }
        section.put("/**", "authc");
        for(String s : section.keySet()){
            System.out.println(s + "----"+ section.get(s)+"-----------section");
        }
        return section;
    }
	
	@Override
	public Class<?> getObjectType() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public boolean isSingleton() {
		// TODO Auto-generated method stub
		return false;
	}
}
